package com.sychip.fhc.app.drawer.screen.components

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.calculatePan
import androidx.compose.foundation.gestures.calculateZoom
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.BottomSheetScaffold
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DatePicker
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.material3.SelectableDates
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.rememberBottomSheetScaffoldState
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.sychip.fhc.app.todo.R
import kotlinx.coroutines.launch
import java.util.Calendar
import java.util.TimeZone

data class Profession(var text: String, var value: MutableState<Boolean> = mutableStateOf(false))

val spaceModifier = Modifier.height(20.dp)


@Preview
@Composable
fun ZoomImageViewComposable() {
    // Reacting to state changes is the core behavior of Compose. We use the state composable
    // that is used for holding a state value in this composable for representing the current
    // value scale(for zooming in the image) & translation(for panning across the image). Any
    // composable that reads the value of counter will be recomposed any time the value changes.
    // This ensures that only the composables that depend on this will be redraw while the
    // rest remain unchanged. This ensures efficiency and is a performance optimization. It
    // is inspired from existing frameworks like React.
    var scale by remember { mutableStateOf(1f) }
    var offsetX by remember { mutableStateOf(0f) }
    var offsetY by remember { mutableStateOf(0f) }

    val height =
        with(LocalDensity.current) { LocalConfiguration.current.screenHeightDp.toDp().toPx() }

    // Column is a composable that places its children in a vertical sequence. You
    // can think of it similar to a LinearLayout with the vertical orientation.
    // In addition we also pass a few modifiers to it.

    // You can think of Modifiers as implementations of the decorators pattern that are used to
    // modify the composable that its applied to. In the example below, we make the Column composable
    // zoomable by leveraging the Modifier.pointerInput modifier
    Column(
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .pointerInput(Unit) {
                awaitEachGesture {
                        awaitFirstDown()
                        do {
                            val event = awaitPointerEvent()
                            scale = (scale * event.calculateZoom()).coerceIn(1F, 3F)
                            val offset = event.calculatePan()
                            //when zooms in or out image so here [coerceIn] coerces image width and height
                            //and limiting its zoom.
                            offsetX = (offsetX + offset.x)
                                .coerceIn(
                                    -((scale - 1F).coerceIn(
                                        0F,
                                        1F
                                    ) * (size.width.toFloat() * .33F) * scale),
                                    ((scale - 1F).coerceIn(
                                        0F,
                                        1F
                                    ) * (size.width.toFloat() * .33F) * scale)
                                )
                            offsetY = (offsetY + offset.y)
                                .coerceIn(
                                    -((scale - 1F).coerceIn(0F, 1F) * (height * .33F) * scale),
                                    ((scale - 1F).coerceIn(0F, 1F) * (height * .33F) * scale)
                                )
                        } while (event.changes.any { it.pressed })
                    }

            }
    ) {
        // There are multiple methods available to load an image resource in Compose.
        // However, it would be advisable to use the painterResource method as it loads
        // an image resource asynchronously
        val imagepainter = painterResource(id = R.drawable.murata_bike)
        // Image is a pre-defined composable that lays out and draws a given [ImageBitmap].
        // We use the graphicsLayer modifier to modify the scale & translation of the image.
        // This is read from the state properties that we created above.
        Image(
            modifier = Modifier
                .fillMaxSize()
                .graphicsLayer(
                    scaleX = scale,
                    scaleY = scale,
                    translationX = offsetX,
                    translationY = offsetY
                ),
            painter = imagepainter,
            contentDescription = "Landscape Image"
        )
    }
}

@Preview(showBackground = true)
@Composable
private fun SwitchComponents() {

    var simpleSwitchState by remember { mutableStateOf(false) }
    var customEnableColorSwitchState by remember { mutableStateOf(true) }
    var customDisableColorSwitchState by remember { mutableStateOf(false) }
    var customEnableTrackColorSwitchState by remember { mutableStateOf(true) }
    var customDisableTrackColorSwitchState by remember { mutableStateOf(false) }

    Column(
        Modifier
            .padding(top = 10.dp)
            .wrapContentSize(Alignment.TopCenter)
    ) {
        // Basic Switch
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween,
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()
        ) {
            Text(text = "Simple Switch.", modifier = Modifier.padding(end = 5.dp))
            Switch(
                checked = simpleSwitchState,
                onCheckedChange = { simpleSwitchState = it }
            )
        }

        // Switch with selected thumb color
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween,
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()
        ) {
            Text(text = "Custom selected thumb color.", modifier = Modifier.padding(end = 5.dp))
            Switch(
                checked = customEnableColorSwitchState,
                onCheckedChange = { customEnableColorSwitchState = it },
                colors = SwitchDefaults.colors(
                    checkedThumbColor = Color.Blue
                ),
                modifier = Modifier.padding(5.dp)
            )
        }

        // Switch with unselected thumb color
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween,
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()
        ) {
            Text(
                text = "Custom unselected thumb color.",
                modifier = Modifier.padding(end = 5.dp)
            )
            Switch(
                checked = customDisableColorSwitchState,
                onCheckedChange = { customDisableColorSwitchState = it },
                colors = SwitchDefaults.colors(
                    uncheckedThumbColor = Color.Black
                ),
                modifier = Modifier.padding(5.dp)
            )
        }

        // Switch with selected track color
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween,
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()
        ) {
            Text(text = "Custom selected track color.", modifier = Modifier.padding(end = 5.dp))
            Switch(
                checked = customEnableTrackColorSwitchState,
                onCheckedChange = { customEnableTrackColorSwitchState = it },
                colors = SwitchDefaults.colors(
                    checkedTrackColor = Color.Blue
                ),
                modifier = Modifier.padding(5.dp)
            )
        }

        // Switch with unselected track color
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween,
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()
        ) {
            Text(
                text = "Custom unselected track color.",
                modifier = Modifier.padding(end = 5.dp)
            )
            Switch(
                checked = customDisableTrackColorSwitchState,
                onCheckedChange = { customDisableTrackColorSwitchState = it },
                colors = SwitchDefaults.colors(
                    uncheckedTrackColor = Color.Blue
                ),
                modifier = Modifier.padding(5.dp)
            )
        }

        // Disabled Switch in OFF state
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween,
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()
        ) {
            Text(text = "Disabled switch in OFF state", modifier = Modifier.padding(end = 5.dp))
            Switch(
                checked = false,
                onCheckedChange = { },
                enabled = false,
                modifier = Modifier.padding(5.dp)
            )
        }

        // Disabled Switch in ON state
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween,
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()
        ) {
            Text(text = "Disabled switch in ON state.", modifier = Modifier.padding(end = 5.dp))
            Switch(
                checked = true,
                onCheckedChange = { },
                enabled = false,
                modifier = Modifier.padding(5.dp)
            )
        }
    }
}

//@Preview
//@Composable
//fun CheckBoxSample() {
//
//    /* Here Create State of checkbox */
//    val mItemsList = remember {
//        mutableStateOf(
//            listOf(
//                Profession("Android"),
//                Profession("iOS"),
//                Profession("Angular"),
//                Profession("Python"),
//                Profession("Electron")
//            )
//        )
//    }
//
//    val (isClick, toggleClick) = remember { mutableStateOf(true) }
//
//    Column(Modifier.background(MaterialTheme.colorScheme.background).fillMaxHeight()) {
//        Column(Modifier.padding(20.dp)) {
//            Text("Select your interested area :", style = MaterialTheme.typography.headlineSmall)
//            Spacer(Modifier.requiredHeight(24.dp))
//            mItemsList.value.forEachIndexed { index, items ->
//                Row(
//                    modifier = Modifier.padding(bottom = 10.dp),
//                    verticalAlignment = Alignment.CenterVertically
//                ) {
//                    Checkbox(
//                        checked = mItemsList.value[index].value.value,
//                        onCheckedChange = { mItemsList.value[index].value.value = it },
//                        enabled = true,
//                        colors = CheckboxDefaults.colors(
//                            checkedColor = MaterialTheme.colorScheme.secondary,
//                            uncheckedColor = Color.DarkGray,
//                            checkmarkColor = Color.White
//                        )
//                    )
//                    Text(
//                        text = items.text,
//                        modifier = Modifier.padding(start = 10.dp),
//                        fontSize = 16.sp
//                    )
//                }
//            }
//            Spacer(Modifier.requiredHeight(24.dp))
//            Text("Clickable label checkbox :", style = MaterialTheme.typography.headlineSmall)
//            Row(
//                modifier = Modifier
//                    .padding(top = 16.dp)
//                    .toggleable(
//                        value = isClick, onValueChange = toggleClick
//                    ),
//                verticalAlignment = Alignment.CenterVertically,
//            ) {
//                Checkbox(
//                    checked = isClick, onCheckedChange = null,
//                    colors = CheckboxDefaults.colors(
//                        checkedColor = MaterialTheme.colorScheme.primary,
//                        uncheckedColor = Color.DarkGray,
//                        checkmarkColor = Color.White
//                    )
//                )
//                Text(
//                    text = "Checkbox label", Modifier.padding(start = 5.dp), fontSize = 16.sp
//                )
//            }
//        }
//    }
//}

@Preview(showBackground = true)
@Composable
private fun RadioGroupSample() {
    /* Here Create List for radioButton */
    val radioOptions = listOf("Red Color", "Blue Color", "Black Color", "White Color")
    /* Here Create State of radioButton */
    var selectedOption by remember { mutableStateOf("") }

    Card(
        colors =  CardDefaults.cardColors(containerColor = Color.Transparent),
        modifier = Modifier
            .padding(vertical = 10.dp)
            .fillMaxWidth(),
        elevation =CardDefaults.elevatedCardElevation(defaultElevation =0.dp ) ,
        shape = RoundedCornerShape(8.dp),
        border = BorderStroke(2.dp, MaterialTheme.colorScheme.primary.copy(0.5f)),
    ) {

        Column(Modifier.padding(10.dp)) {
            Text(
                text = "Radio Group example :",
                style = MaterialTheme.typography.headlineSmall
            )

            Spacer(spaceModifier)

            radioOptions.forEach { text ->
                Row(Modifier
                    .padding(bottom = 10.dp)
                    .wrapContentSize()
                    .clickable(
                        onClick = {
                            selectedOption = text

                        }
                    ), verticalAlignment = Alignment.CenterVertically
                ) {
                    RadioButton(
                        selected = (text == selectedOption),
                        onClick = {
                            selectedOption = text

                        },
                        colors = RadioButtonDefaults.colors(selectedColor = MaterialTheme.colorScheme.primary)
                    )
                    Text(
                        text = text,
                        modifier = Modifier.padding(start = 10.dp, end = 20.dp),
                        textAlign = TextAlign.Center,
                        fontSize = 15.sp
                    )
                }
            }
        }
    }
}

@Preview
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SimpleBottomSheetScaffold(modifier:Modifier = Modifier) {
    val scope = rememberCoroutineScope()
    val scaffoldState = rememberBottomSheetScaffoldState()

    BottomSheetScaffold(
        modifier = modifier,
        scaffoldState = scaffoldState,
        sheetPeekHeight = 128.dp,
        sheetContent = {
            Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
                Box(Modifier
                    .fillMaxWidth()
                    .height(128.dp), contentAlignment = Alignment.Center) {
                    Text("Swipe up to expand sheet")
                }
                Text("Sheet content")
                Button(
                    modifier = Modifier.padding(bottom = 64.dp),
                    onClick = { scope.launch { scaffoldState.bottomSheetState.partialExpand() } }
                ) {
                    Text("Click to collapse sheet")
                }
            }
        }
    ) { innerPadding ->
        Column (
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding),
        ) {
            Text("Scaffold Content")





        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Preview(showBackground = true)
@Composable
fun CustomModalBottomSheetDemo(modifier: Modifier = Modifier){
    // 分享
    val sheetState = rememberModalBottomSheetState()
    var visible by remember { mutableStateOf(false) }
    Row {
        Button(onClick = {visible = !visible
        }) {
            Text(text = "Bottom Sheet DatePicker", color = Color.White)
        }
    }

    if (visible) {
        ModalBottomSheet(
            modifier = modifier,
            onDismissRequest = {
                visible = false
            },
            sheetState = sheetState
        ) {
            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                val datePickerState =
                    rememberDatePickerState(
                        selectableDates =
                        object : SelectableDates {
                            // Blocks Sunday and Saturday from being selected.
                            override fun isSelectableDate(utcTimeMillis: Long): Boolean {
//                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                                    val dayOfWeek =
//                                        Instant.ofEpochMilli(utcTimeMillis)
//                                            .atZone(ZoneId.of("UTC"))
//                                            .toLocalDate()
//                                            .dayOfWeek
//                                    return dayOfWeek != DayOfWeek.SUNDAY && dayOfWeek != DayOfWeek.SATURDAY
//                                }
                                val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
                                calendar.timeInMillis = utcTimeMillis
                                return calendar[Calendar.DAY_OF_WEEK] != Calendar.SUNDAY && calendar[Calendar.DAY_OF_WEEK] != Calendar.SATURDAY
                            }

                            // Allow selecting dates from year 2023 forward.
                            override fun isSelectableYear(year: Int): Boolean {
                                return year > 2022
                            }
                        }
                    )

                Column(
                    modifier = Modifier.verticalScroll(rememberScrollState()),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    DatePicker(state = datePickerState)
                    Text(
                        "Selected date timestamp: ${datePickerState.selectedDateMillis ?: "no selection"}",
                        modifier = Modifier.align(Alignment.CenterHorizontally)
                    )
                }

            }

        }
    }

}